//
//  JMOriginCardNumVC.m
//  NewiOSProject
//
//  Created by apple on 2023/9/20.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMOriginCardNumVC.h"
#import "JMSlicenseVC.h"
#import "JMChangeMyBankController.h"
#import "BMTextField.h"
#import "JMPermissionHelper.h"



@interface JMOriginCardNumVC ()
{
    UITextField *textF;
    BOOL livenessCheckResult;
}
@property (nonatomic, strong)JMLoadingButton *loginBtn;
@property (nonatomic, strong)UILabel *messagelab;
//活体渠道
@property (nonatomic, strong)NSString * curChannel;
//活体检测id
@property (nonatomic, strong)NSString * livenessId;
//活体检测返回图片
@property (nonatomic, strong)NSString * photoName;
@end

@implementation JMOriginCardNumVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.TitleLabel.text = @"Modificar cuenta bancaria";
    self.view.backgroundColor = WhiteColor();
    
    UILabel *titleLab = [JMControl createLabelWithFrame:(CGRectMake(24, NAVIGATION_BAR_HEIGHT()+30, kAppW()-40, 48)) Font:Font(14) Text:@"Número de cuenta CLABE o tarjeta \nbancaria original " color:Text_COLOR_LEVEL2() textAlignment:0 numberOfLine:0];
    [self.view addSubview:titleLab];
    
    textF = [JMControl creatBMTextfieldWithFrame:(CGRectMake(24, titleLab.bottom+10, kAppW()-48, 54)) placeholder:@"Por favor escribe" delegate:nil textfieldTextFont:Font(16) clearButtonMode:UITextFieldViewModeWhileEditing keyboardType:(UIKeyboardTypeDefault)];
    textF.cornerRadius = 12;
    textF.keyboardType = UIKeyboardTypeNumberPad;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:textF];
    [self.view addSubview:textF];
    
    [JMControl addHorLineWithSpaceWithDefaultColor:24 top:textF.bottom height:1 toView:self.view];
    
    UIButton * delegateBtn = [JMControl createButtonWithFrame:(CGRectMake(0, kAppH()-50-kSafeAreaBottomHeight(), kAppW(), 37)) Target:self Action:@selector(delegateBtnClick) Title:@"《 Politica de privacidad 》" titlColor:Hex_Str_COLOR(@"#222222") font:Font(12) tag:1 backgroundColor:UIColor.clearColor];
     [self.view addSubview:delegateBtn];
    
   _loginBtn =  [[JMLoadingButton alloc]initWithFrame:(CGRectMake(24, delegateBtn.top-76, kAppW()-48, 56)) title:@"Entregar" font:Font(16) titleLabelColor:Button_ENABLE_TEXTCOLOR() backgoundColor:Button_ENABLE_BG_COLOR() action:@selector(loginBtnClick) target:self];
    _loginBtn.enable = NO;
    _loginBtn.cornerRadius = 28;
    [self.view addSubview:_loginBtn];

}
//这里可以通过发送object消息获取注册时指定的UITextField对象
- (void)textFieldDidChangeValue:(NSNotification *)notification{
    UITextField *sender = (UITextField *)[notification object];
    if(sender.text.length){
        self.loginBtn.enable = YES;
    }else{
        self.loginBtn.enable = NO;
    }
    
}
-(void)delegateBtnClick{
    [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(loginPrivacyAgreement) andTitle:@"Politica de privacidad"];
}
//获取验证码
-(void)loginBtnClick{
    NSDictionary *param;
    param =  @{@"bankCard":textF.text};
    
    [self.loginBtn startLoading];
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/auth/check-origin-bankcard") params:param success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        NSNumber *num = dataDic;
        [self.loginBtn endLoading];
        if ([self.step isEqualToString:@"check_origin&liveness"]) {
            [[JMPermissionHelper sharedInstance] accessCamera:^(BOOL granted) {
                if (granted) {
                    [self getLiveConfig];
                }
            }];
        }else{
            JMChangeMyBankController *vc = JMChangeMyBankController.new;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    } fail:^(NSString * _Nonnull errorMsg) {
        [self.loginBtn endLoading];
        [self createLabWith:errorMsg];
    }];
    
}
-(void)createLabWith:(NSString *)message{
    if ([message isKindOfClass:NSString.class]) {
        [_messagelab removeFromSuperview];
        _messagelab = [JMControl createAutoHeightLabelWithOrgin:(CGPointMake(textF.left, textF.bottom+20)) andWidth:kAppW()-textF.left*2 Font:Font(12) Text:message color:Hex_Str_COLOR(@"#FF3F33")];
        [self.view addSubview:_messagelab];
    }
}
//2.2获取活体渠道 检查是否需要活体检验
-(void)getLiveConfig{
    [[JMBaseRequest sharedInstance]  requestBasePost:BasePostRequestUrl(@"/api/auth/livenConfig") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        
        NSNumber * isSkip =dataDic[@"skipLiven"];
        if(isSkip.intValue){
            [self stopAnimating];
            [self goNewCardVC];
        }else{
            //2.检查用户是否可以做某项授权接口
            self.curChannel = dataDic[@"livenChannel"];

            [self checkAuthResultWithChannelWith:self.curChannel];
        }
    } fail:^(NSString * _Nonnull errorMsg) {
        [self stopAnimating];
        [self showMessage:errorMsg];
    }];
    
}
-(void)goNewCardVC{
    [self stopAnimating];
    JMChangeMyBankController *vc = JMChangeMyBankController.new;
    [self.navigationController pushViewController:vc animated:YES];
}

//AdvanceSDK检测
-(void)showAdvanceLivenessSDK{
    
}
//SDK 活体 image上传获取photoName
-(void)uploadLivenessImg:(UIImage *)ossImg{

    NSString *path = [NSString stringWithFormat:@"/api/auth/modify-bankcard-live?livenChannelEnum=%@",self.curChannel];
    NSURL *url = [NSURL URLWithString: BasePostRequestUrl(path)];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    NSString *token = [NSString stringWithFormat:@"%@", JMProjectManager.sharedJMProjectManager.loginUser.token];
    [request setValue: token forHTTPHeaderField:@"loginToken"];
    [request setValue:@"1.0.0" forHTTPHeaderField:@"x-version"];
    [request setValue:@"1.0.0" forHTTPHeaderField:@"versionNumber"];
    [request setValue:bundleId forHTTPHeaderField:@"x-package-name"];
    [request setValue:bundleId forHTTPHeaderField:@"bagName"];
    NSString *boundary = [self generateBoundaryString];

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
    NSMutableData *formData = [NSMutableData data];
    [formData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [formData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [formData appendData:[@"Content-Disposition: form-data; name=\"photo\"; filename=\"photo.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [formData appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *imgData =  [self compressImage:ossImg toMaxSize:300];
    [formData appendData:imgData]; // 替换为你的图像
    [formData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [formData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:formData];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil && data != nil) {
         
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            if (content != nil) {
                NSDictionary *data = (NSDictionary *)content[@"data"];
                NSLog(@"上传图片成功content-------%@",content);
                NSDictionary *tongDunOCRResponseEntity = (NSDictionary *)content[@"tongDunOCRResponseEntity"];
                
                if (data != nil) {
                    NSString *photoName = data[@"photoName"];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.photoName = photoName;
                        [self configLivenessResult:self.livenessId];
                    });
                }
            }
        }else{
            
        }
    }];

    [task resume];
}
//4.检测结果预处理
-(void)configLivenessResult:(NSString *)livenessId{
    [[JMBaseRequest sharedInstance]  requestBasePost:BasePostRequestUrl(@"/api/auth/pre-liveness") params:@{@"livenessId":livenessId} success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        livenessCheckResult = YES;
        [self checkLivenessResult:livenessId];
    } fail:^(NSString * _Nonnull errorMsg) {
        livenessCheckResult = NO;
    }];
}
-(void)checkLivenessResult:(NSString *)livenessId{
    [[JMBaseRequest sharedInstance]  requestBasePost:BasePostRequestUrl(@"/api/auth/check-modify-bankcard-live") params:@{@"livenessId":livenessId,@"livenessImg":self.photoName,@"livenChannelEnum":self.curChannel} success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        livenessCheckResult = YES;
        [self goNewCardVC];
    } fail:^(NSString * _Nonnull errorMsg) {
        livenessCheckResult = NO;
    }];
}
//3.检测用户是否可以进行认证（在首页进入时 如果获取的步骤是第三步，就要直接调用该接口，失败直接谈提示框，并不能进入认证）
-(void)checkAuthResultWithChannelWith:(NSString *)livenChannel{
    
    [[JMBaseRequest sharedInstance]  requestBasePost:BasePostRequestUrl(@"/api/auth/check") params:@{@"authType":@"LIVENESS"} success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        BOOL checkout = dataDic[@"checkResult"];
        [self stopAnimating];
        if(checkout){
            if([livenChannel isEqualToString:@"SILENCE_LIVENESS"]){//静默活体（按新增的UI来做就行）
                [self stopAnimating];
                JMSlicenseVC *vc = JMSlicenseVC.new;
                vc.verifyResultBlock = ^(NSDictionary * _Nonnull dict) {
                    [self goNewCardVC];
                };
                [self.navigationController pushViewController:vc animated:YES];
            } else if([livenChannel isEqualToString:@"CLOUDUN"]){//Cloudn活体
                [self stopAnimating];
            } else{//Advance
                [self getLicense];
            }
        }else{
            [self showMessage:@"Lo sentimos. Aún no es la fecha del evento"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } fail:^(NSString * _Nonnull errorMsg) {
        [self stopAnimating];
    }];
}

-(void)getLicense{
    
}
// 压缩图片到指定大小（以KB为单位）
- (NSData *)compressImage:(UIImage *)image toMaxSize:(NSUInteger)maxSizeInKB {
    CGFloat compressionQuality = 1.0;
    NSData *compressedImageData = UIImageJPEGRepresentation(image, compressionQuality);
    
    while ([compressedImageData length] > maxSizeInKB * 1024 && compressionQuality > 0.0) {
        compressionQuality -= 0.1;
        compressedImageData = UIImageJPEGRepresentation(image, compressionQuality);
    }
    
    return compressedImageData;
}
//MARK: - DetectViewControllerDelegate
- (void)detectFailed:(nonnull NSString *)livenessId errorCode:(NSInteger)errorCode errorMessage:(nonnull NSString *)errorMessage {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)detectSuccess:(nonnull NSString *)livenessId livenessBitmap:(nonnull UIImage *)livenessBitmap livenessBitmapBase64Str:(nonnull NSString *)livenessBitmapBase64Str {
    self.livenessId = livenessId;
  
    [self uploadLivenessImg:livenessBitmap];
  
}
@end
